package algorithm.monotonousStack;

public class MaximalRectangle {

    public static int maximalRectangle(char[][] matrix){
        int[] height = new int[matrix[0].length];
        int max = Integer.MIN_VALUE;
        int[] stack = new int[height.length];
        int last = -1;
        for (int i = 0; i < matrix.length; i++) {
            for (int j = 0; j < height.length; j++) {
                if(matrix[i][j] == '0')
                    height[j] = 0;
                else
                    height[j]++;
            }
            last = -1;
            for (int j = 0; j < height.length; j++) {
                while(last != -1 && height[stack[last]] >= height[j]){
                    int pop = stack[last--];
                    int start = last == -1 ? -1 : stack[last];
                    int end = j - 1;
                    max = Math.max(max, (end - start) * height[pop]);
                }
                stack[++last] = j;
            }
            while(last != -1){
                int pop = stack[last--];
                int start = last == -1 ? -1 : stack[last];
                int end = height.length - 1;
                max = Math.max(max, (end - start) * height[pop]);
            }

        }
        return max;
    }

    public static void main(String[] args) {

    }
}
